package com.sky.service;

import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import nonapi.io.github.classgraph.utils.Join;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.service.AutoFill)")
    public void pt() {
    }

    @Before("pt()")
    public void bbf(JoinPoint jopt) {

        MethodSignature msms = (MethodSignature) jopt.getSignature();
        AutoFill aaf = msms.getMethod().getAnnotation(AutoFill.class);
        OperationType opt = aaf.value();

        Object[] args = jopt.getArgs();
        if (args.length == 0) return;
        Object arg1 = args[0];

        LocalDateTime now = LocalDateTime.now();
        Long cid = BaseContext.getCurrentId();

        try {
            if (opt == OperationType.INSERT) {
                Method setCreateTime = arg1.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setUpdateTime = arg1.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = arg1.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method setCreateUser = arg1.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);

                setCreateUser.invoke(arg1, cid);
                setUpdateUser.invoke(arg1, cid);
                setUpdateTime.invoke(arg1, now);
                setCreateTime.invoke(arg1, now);


            } else if (opt == OperationType.UPDATE) {
                Method setUpdateTime = arg1.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = arg1.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setUpdateUser.invoke(arg1, cid);
                setUpdateTime.invoke(arg1, now);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
